//
//  HJHomeViewController.m
//  12期传智微博HJ
//
//  Created by mac on 15-2-1.
//  Copyright (c) 2015年 jun. All rights reserved.
//

#import "HJHomeViewController.h"
#import "HJTitleButton.h"
#import "HJDefaultCenterView.h"
#import "IWStatus.h"
#import "IWUser.h"
#import "IWPhoto.h"
#import "HJTableFooterView.h"
@interface HJHomeViewController()
/**
 *  微博数组
 */
@property(nonatomic, strong) NSMutableArray *statuses;
@end
@implementation HJHomeViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    //初始化导航条
    [self setupNav];
    //初始化默认界面
    if (self.defaultCenterView != nil) {
        self.defaultCenterView.iconImageName = @"visitordiscover_feed_image_house";
        self.defaultCenterView.info = @"当你关注一些人以后，他们发布的最新消息会显示在这里";

    }else{
        //获取用户信息
        [self setupUserInfo];
        //添加下拉刷新
        [self setupRefresh];
    }
    
    
    
}
#pragma mark - 加载微博数据
- (void)loadNewStatues:(UIRefreshControl *)refreshControl
{
    //创建网络管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //封装请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"]= [HJAccount accountFromSandbox].access_token;
    //取出数组元素的第一个ID
    NSString *firstStatusIdstr = [[self.statuses firstObject] idstr];
    if (firstStatusIdstr != nil) {
        parameters[@"since_id"] = firstStatusIdstr;
    }
    //发出请求
    NSString *urlString = @"https://api.weibo.com/2/statuses/home_timeline.json";
    [manager GET:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //存储获取的微博数据
        NSArray *newStatus = responseObject[@"statuses"];
        //字典转模型
        NSArray *models = [IWStatus objectArrayWithKeyValuesArray:newStatus];
        
        NSRange range = NSMakeRange(0, models.count);
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.statuses insertObjects:models atIndexes:indexSet];
        //刷新表格
        [self.tableView reloadData];
        //关闭刷新控件
        [self.tableView headerEndRefreshing];
       // [refreshControl endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
       // [refreshControl endRefreshing];
        [self.tableView headerEndRefreshing];
    }];
}
/**
 *  添加刷新
 *
 *  @return <#return value description#>
 */
- (void)setupRefresh
{
//    //创建刷新控件
//    UIRefreshControl *refreshcontrol = [[UIRefreshControl alloc]init];
//    //监听刷新时间
//    [refreshcontrol addTarget:self action:@selector(loadNewStatues:) forControlEvents:UIControlEventValueChanged];
//    [self.tableView addSubview:refreshcontrol];
//    
//    //主动刷新
//    //系统自带的下拉刷新控件, 主动调用beginRefreshing方法之后只会显示刷新控件, 并不会促发刷新监听事件
//    [refreshcontrol beginRefreshing];
//    
//    //主动调用加载方法
//    [self loadNewStatues:refreshcontrol];
    //1.添加下拉刷新
    [self.tableView addHeaderWithTarget:self action:@selector(loadNewStatues:)];
    //添加上拉家在更多
    [self.tableView addFooterWithTarget:self action:@selector(loadMoreStatues)];
    
    //主动显示下拉刷新,促发下拉方法
    [self.tableView headerBeginRefreshing];
}
- (void)loadMoreStatues
{
    //创建网络管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //封装请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"]= [HJAccount accountFromSandbox].access_token;
    //取出数组元素的第一个ID
    NSNumber *firstStatusIdstr = @([[[self.statuses lastObject] idstr] longLongValue] - 1);
    if (firstStatusIdstr != nil ) {
        parameters[@"max_id"] = firstStatusIdstr;
    }
    //发出请求
    NSString *urlString = @"https://api.weibo.com/2/statuses/home_timeline.json";
    [manager GET:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //存储获取的微博数据
        NSArray *newStatus = responseObject[@"statuses"];
        //字典转模型
        NSArray *models = [IWStatus objectArrayWithKeyValuesArray:newStatus];
        
        NSRange range = NSMakeRange(0, models.count);
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.statuses insertObjects:models atIndexes:indexSet];
        //刷新表格
        [self.tableView reloadData];
        //关闭刷新控件
        [self.tableView footerEndRefreshing];
        // [refreshControl endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        // [refreshControl endRefreshing];
        [self.tableView footerEndRefreshing];
    }];

}
#pragma mark - 初始化方法
- (void)setupUserInfo
{
    //创建请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //封装请求参数
    NSMutableDictionary *paraments = [NSMutableDictionary dictionary];
    //取出授权模型
    HJAccount *account = [HJAccount accountFromSandbox];
    paraments[@"access_token"] = account.access_token;
    paraments[@"uid"] = account.uid;
    
    //发送请求
    NSString *urlString = @"https://api.weibo.com/2/users/show.json";
    [manager GET:urlString parameters:paraments success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //取出获取得到用户头像
        NSString *iconURLstr = responseObject[@"profile_image_url"];
        //判断当前头像是否跟存储的一直
        if ([account.profile_image_url isEqualToString:iconURLstr]) {
            return ;
        }
        //如果不一致 更新头像
        account.profile_image_url = iconURLstr;
        [account save];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"失败****%@",error);
    }];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //旋转
    if (self.defaultCenterView != nil) {
         [self.defaultCenterView startRotate];
    }
   
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.defaultCenterView != nil) {
         [self.defaultCenterView stopRotate];
    }
}
- (void)setupNav
{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"navigationbar_friendsearch" higImage:@"navigationbar_friendsearch_highlighted" target:self action:@selector(firendSearch)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"navigationbar_pop" higImage:@"navigationbar_pop_highlighted" target:self action:@selector(scan)];
    
    HJTitleButton *titleBtn = [[HJTitleButton alloc]init];
    // titleBtn.backgroundColor = [UIColor blackColor];
    
    [titleBtn setTitle:@"首页" forState:UIControlStateNormal];
    // 设置默认状态图片
    [titleBtn setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    // 设置选中状态图片
    [titleBtn setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateSelected];
    
    [titleBtn sizeToFit];
    
    [titleBtn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    
    self.navigationItem.titleView = titleBtn;
}
#pragma mark - 内部控制方法
UIWindow *_window;
- (void)titleBtnClick:(HJTitleButton *)tittleBtn
{
    tittleBtn.selected = !tittleBtn.selected;
    
    UITableView *tb = [[UITableView alloc]init];
    tb.size = CGSizeMake(150, 200);
    
    //2.显示菜单
    
    //2.1创建菜单容器
    UIImageView *menuView = [[UIImageView alloc]init];
    //开始view的可触发事件
    menuView.userInteractionEnabled = YES;
    UIImage *image = [UIImage imageNamed:@"popover_background"];
    menuView.image = image;
    //2.2添加内容视图
    //设置内容得X和Y值
    tb.x = 15;
    tb.y = 18;
    [menuView addSubview:tb];
    //2.3设置菜单内容的frame
    CGFloat menuViewCenterX = [UIScreen mainScreen].bounds.size.width * 0.5;
    CGFloat menuViewY = 64 - 10;
    CGFloat menuViewW = CGRectGetMaxX(tb.frame) + tb.x;
    CGFloat menuViewH = CGRectGetMaxY(tb.frame) + tb.y;
    menuView.frame = CGRectMake(0, menuViewY, menuViewW, menuViewH);
    
    menuView.centerX = menuViewCenterX;
    
    //[self.navigationController.view addSubview:menuView];
    //创建蒙版
    UIButton *cover = [[UIButton alloc]init];
    cover.frame = [UIScreen mainScreen].bounds;
    cover.backgroundColor = [UIColor clearColor];
    [cover addTarget:self action:@selector(coverClick:) forControlEvents:UIControlEventTouchUpInside];
    //将菜单添加到蒙版上
    [cover addSubview:menuView];
    
    _window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    _window.hidden = NO;
    
    _window.windowLevel = UIWindowLevelAlert;
    
    [_window addSubview:cover];
    
    

}
- (void)coverClick:(UIButton *)btn
{
    _window = nil;
    
}
- (void)firendSearch
{
    
}
- (void)scan
{
    
}
#pragma mark - 数据源方法
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"====%ld",self.statuses.count
          );
    return self.statuses.count;
   
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
        
    }
    //设置数据
    //取出对应行的微博模型
    IWStatus *status = self.statuses[indexPath.row];
    //从对应行的微博模型取出对应的用户模型
    IWUser *user = status.user;
    //设置昵称
    cell.textLabel.text = user.name;
    //设置微博内容
    cell.detailTextLabel.text = status.text;
    //设置用户偷袭
    NSURL *iconUrlString = [NSURL URLWithString:user.profile_image_url];
    [cell.imageView sd_setImageWithURL:iconUrlString placeholderImage:[UIImage imageNamed:@"avatar_default_big"]];
    
    
    return cell;
}
- (NSMutableArray *)statuses
{
    if (!_statuses) {
        _statuses = [NSMutableArray array];
    }
    return _statuses;
}

@end
